package edu.ccit.shudong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ccit.shudong.dto.NewCommentDto;
import edu.ccit.shudong.entity.NewComment;
import edu.ccit.shudong.mapper.NewCommentMapper;
import edu.ccit.shudong.service.NewCommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class NewCommentServiceImpl extends ServiceImpl<NewCommentMapper, NewComment> implements NewCommentService {
    @Override
    public List<NewCommentDto> getListWithReplyByPostId(Long id) {
        LambdaQueryWrapper<NewComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NewComment::getPostId, id);
        List<NewComment> list = this.list(queryWrapper);
        return this.transListToTreeData(list, null);
    }

    public List<NewCommentDto> transListToTreeData(List<NewComment> list, Long rootValue) {
        List<NewCommentDto> result = new ArrayList<>();
        for (NewComment item : list) {
            NewCommentDto newCommentDto = new NewCommentDto();
            BeanUtils.copyProperties(item, newCommentDto);
            if(Objects.equals(newCommentDto.getPId(), rootValue)) {
                result.add(newCommentDto);
                List<NewCommentDto> childList = transListToTreeData(list, newCommentDto.getId());
                if(!childList.isEmpty()) {
                    newCommentDto.setChildren(childList);
                }
            }
        }
        return result;
    }
}
